<!--created by yuyupeng-->
<!--2023/11/29-->
<!-- 业务实体与sql关系维护 -->
<template>
  <div>
    <!-- 查询表单 -->
    <AdvancedSearch
      ref="searchRef"
      :data-source="searchItemList"
      @change="searchByParams"
    />
    <a-space style="margin-top: 5px; margin-bottom: 5px">
      <a-button type="primary" @click="showAddModal"
        ><icon-plus />新增业务实体与SQL关系</a-button
      >
    </a-space>
    <!-- 表格 -->
    <a-table
      v-model:selectedKeys="selectedKeys"
      row-key="id"
      column-resizable
      :columns="tbCols"
      :data="tbData"
      :pagination="pagination"
      :loading="tbLoading"
      :scroll="{ x: '100%', y: 600 }"
      :scrollbar="true"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
    >
      <!-- 插槽-一键复制 -->
      <template #quickCopyToolTip="{ record, column }">
        <quick-copy-tool-tip
          :show-text="record[column['dataIndex']]"
          show-btn
        />
      </template>
      <!-- 插槽-操作 -->
      <template #operation="{ record }">
        <a-space>
          <a-link type="text" @click="showEditModal(record)"> 修改 </a-link>
          <a-link type="text" @click="showPreviewJsonModal(record)">
            数据预览
          </a-link>
          <a-popconfirm
            content="确定删除吗?"
            type="warning"
            @ok="deleteTbData(record.id)"
          >
            <a-link type="text">删除</a-link>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>
    <!-- 新增业务实体与SQL关系弹窗 -->
    <AdvancedFormModal
      ref="addModalRef"
      width="900px"
      title="新增业务实体与SQL关系"
      :items="addModalConfig"
      :rules="advancedModalRules"
      :mask-closable="false"
      :submit-with-close="false"
      @ok="addModalSubmit"
    >
      <template #otherSlot>
        <div style="width: 100%">
          <sql-editor ref="sqlEditorAddRef" />
        </div>
      </template>
    </AdvancedFormModal>
    <!-- 修改业务实体与SQL关系弹窗 -->
    <AdvancedFormModal
      ref="editModalRef"
      width="900px"
      title="修改业务实体与SQL关系基本信息"
      :items="editModalConfig"
      :rules="advancedModalRules"
      :submit-with-close="false"
      @ok="editModalSubmit"
    >
      <template #otherSlot>
        <div style="width: 100%">
          <sql-editor
            v-if="currentRecord"
            ref="sqlEditorEditRef"
            :monaco-editor-default-value="currentRecord.defineSql"
          />
        </div>
      </template>
    </AdvancedFormModal>
    <!-- 数据预览弹窗 -->
    <AdvancedFormModal
      ref="previewJsonModalRef"
      width="900px"
      title="数据预览弹窗"
      :items="previewJsonModalConfig"
      :ok-button-props="{ style: { display: 'none' } }"
      :cancel-button-props="{ style: { display: 'none' } }"
    >
      <template #otherSlot>
        <div style="width: 100%">
          <sql-editor
            v-if="previewJsonRecord"
            :monaco-editor-default-value="previewJsonRecord"
            monaco-editor-lang="json"
            monaco-editor-height="600px"
            :read-only="true"
          />
        </div>
      </template>
    </AdvancedFormModal>
  </div>
</template>

<!--新script-->
<script lang="ts" setup>
  import { Notification } from '@arco-design/web-vue';
  import { ref, onMounted, reactive, computed, toRefs } from 'vue';
  import AdvancedSearch from '@/common/components/cac-components/advanced-search/index.vue';
  import AdvancedFormModal from '@/common/components/cac-components/advanced-form-modal/index.vue';
  import QuickCopyToolTip from '@/common/components/cac-components/quickcopy-tooltip/index.vue';
  import { Pagination } from '@/types/global';
  import SqlEditor from '@/views/infrastructure/business-entity/components/sql-editor.vue';
  import {
    BusinessEntityRecord,
    SQLRelevanceEntityRecord,
  } from '@/api/infrastructure/model/businessEntityModal';
  import {
    addSQLRelevanceEntityRecord,
    deleteSQLRelevanceEntityRecord,
    editSQLRelevanceEntityRecord,
    executeSQLRelevanceEntityRecord,
    querySQLRelevanceEntityRecordList,
  } from '@/api/infrastructure/business-entity';
  /**
   * data
   */
  const props = defineProps({
    businessEntity: {
      // 业务实体
      type: Object,
      required: true,
    },
  });
  const { businessEntity } = toRefs(props); // 根据props创建多个 ref 对象
  // 表格
  const tbData = ref<BusinessEntityRecord[]>([]);
  const tbCols = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      fixed: 'left',
      width: 60,
      render: (row: any) => row.rowIndex + 1,
    },
    /* { title: '', dataIndex: 'id', fixed: 'left', ellipsis: true, align: 'center', tooltip: true },
    { title: '查看', fixed: 'left', align: 'center', width: 100, slotName: 'detail' }, */
    {
      title: 'SQL名称',
      dataIndex: 'selectName',
      width: 150,
      align: 'center',
      tooltip: true,
    },
    /* { title: '对应实体的id', dataIndex: 'entityId', width: 150, ellipsis: true, align: 'center' }, */
    {
      title: 'SQL语句',
      dataIndex: 'defineSql',
      width: 300,
      ellipsis: true,
      align: 'center',
      tooltip: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
    },
    /* { title: '创建者', dataIndex: 'creator', width: 150, ellipsis: true, align: 'center' },
    { title: '创建时间', dataIndex: 'createTime', width: 150, ellipsis: true, align: 'center' },
    { title: '更新者', dataIndex: 'updater', width: 150, ellipsis: true, align: 'center' },
    { title: '更新时间', dataIndex: 'updateTime', width: 150, ellipsis: true, align: 'center' },
    { title: '更新ip', dataIndex: 'updateIp', width: 150, ellipsis: true, align: 'center' },
    { title: '是否删除', dataIndex: 'deleted', width: 150, ellipsis: true, align: 'center' }, */
    {
      title: '操作',
      align: 'center',
      fixed: 'right',
      width: 150,
      slotName: 'operation',
    },
  ];
  const searchRef = ref<any>();
  const addModalRef = ref<any>();
  const editModalRef = ref<any>();
  const sqlEditorAddRef = ref<any>();
  const sqlEditorEditRef = ref<any>();
  const previewJsonModalRef = ref<any>();
  const currentRecord = ref<SQLRelevanceEntityRecord>();
  const previewJsonRecord = ref<any>();
  const searchParams = ref<SQLRelevanceEntityRecord>();
  const tbLoading = ref<boolean>(false);
  // 勾选框
  const selectedKeys = ref([]);
  // 分页，默认第1页，每页10条
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    showPageSize: true,
    showTotal: true,
  };
  const pagination = reactive({
    ...basePagination,
  });
  // 搜索项配置
  const searchItemList = [
    /* { type: 'text', labelText: '', fieldName: 'id'}, */
    { type: 'text', labelText: 'SQL名称', fieldName: 'selectName' },
    /* { type: 'text', labelText: '对应实体的id', fieldName: 'entityId'},
    { type: 'text', labelText: 'SQL语句', fieldName: 'otherSlot' },
    /* { type: 'text', labelText: '备注', fieldName: 'remark'},
    { type: 'text', labelText: '创建者', fieldName: 'creator'},
    { type: 'text', labelText: '创建时间', fieldName: 'createTime'},
    { type: 'text', labelText: '更新者', fieldName: 'updater'},
    { type: 'text', labelText: '更新时间', fieldName: 'updateTime'},
    { type: 'text', labelText: '更新ip', fieldName: 'updateIp'},
    { type: 'text', labelText: '是否删除', fieldName: 'deleted'}, */
  ];
  // computed
  // 新增弹窗配置项
  const addModalConfig = computed(() => {
    return [
      /* { type: 'text', labelText: '', fieldName: 'id'}, */
      {
        span: 24,
        type: 'text',
        labelText: '对应实体的id',
        fieldName: 'entityId',
        visible: false,
      },
      { span: 12, type: 'text', labelText: 'SQL名称', fieldName: 'selectName' },
      { span: 12, type: 'text', labelText: '备注', fieldName: 'remark' },
      { span: 24, type: 'other', labelText: 'SQL语句', fieldName: 'otherSlot' },
      /* { type: 'text', labelText: '创建者', fieldName: 'creator'},
      { type: 'text', labelText: '创建时间', fieldName: 'createTime'},
      { type: 'text', labelText: '更新者', fieldName: 'updater'},
      { type: 'text', labelText: '更新时间', fieldName: 'updateTime'},
      { type: 'text', labelText: '更新ip', fieldName: 'updateIp'},
      { type: 'text', labelText: '是否删除', fieldName: 'deleted'}, */
    ];
  });
  // 修改弹窗配置项
  const editModalConfig = computed(() => {
    return [
      {
        span: 24,
        type: 'text',
        labelText: '',
        fieldName: 'id',
        visible: false,
      },
      {
        span: 24,
        type: 'text',
        labelText: '对应实体的id',
        fieldName: 'entityId',
        visible: false,
      },
      { span: 12, type: 'text', labelText: 'SQL名称', fieldName: 'selectName' },
      { span: 12, type: 'text', labelText: '备注', fieldName: 'remark' },
      { span: 24, type: 'other', labelText: 'SQL语句', fieldName: 'otherSlot' },
      /* { type: 'text', labelText: '创建者', fieldName: 'creator'},
      { type: 'text', labelText: '创建时间', fieldName: 'createTime'},
      { type: 'text', labelText: '更新者', fieldName: 'updater'},
      { type: 'text', labelText: '更新时间', fieldName: 'updateTime'},
      { type: 'text', labelText: '更新ip', fieldName: 'updateIp'},
      { type: 'text', labelText: '是否删除', fieldName: 'deleted'}, */
    ];
  });
  // 数据预览弹窗配置项
  const previewJsonModalConfig = computed(() => {
    return [{ span: 24, type: 'other', labelText: '', fieldName: 'otherSlot' }];
  });
  // 弹窗表单项校验配置
  const advancedModalRules = ref({
    selectName: [{ required: true, message: '请输入SQL名称' }],
  });
  /**
   * func
   */
  /**
   * @method
   * @description 获取表格数据
   */
  const getTbData = async () => {
    tbLoading.value = true;
    selectedKeys.value = [];
    try {
      const params: SQLRelevanceEntityRecord = {
        entityId: businessEntity.value.id,
      };
      let { data } = await querySQLRelevanceEntityRecordList(params);
      if (searchParams.value?.selectName) {
        data = data.filter(
          (e) =>
            (e.selectName as string).indexOf(
              searchParams.value?.selectName as string
            ) > -1
        );
      }
      tbData.value = data;
      pagination.total = data.length;
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      tbLoading.value = false;
    }
  };
  /**
   * @method
   * @description 按条件搜索
   */
  const searchByParams = (reqdata: SQLRelevanceEntityRecord = {}) => {
    searchParams.value = reqdata;
    getTbData();
  };
  /**
   * @method
   * @description 页码发生变化触发
   */
  const onPageChange = (current: number) => {
    pagination.current = current;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 数据条数发生变化触发
   */
  const onPageSizeChange = (pageSize: number) => {
    console.log(pageSize);
    pagination.pageSize = pageSize;
    searchRef.value.handleSubmit(); // 与搜索结果保持一致
  };
  /**
   * @method
   * @description 删除业务实体与SQL关系信息
   */
  const deleteTbData = async (id: string) => {
    try {
      const res = (await deleteSQLRelevanceEntityRecord(id)) as any;
      console.log(res);
      if (res.code === 200) {
        Notification.success({
          content: '删除成功！',
        });
      } else {
        Notification.error({
          title: '删除失败！',
          content: res.message,
        });
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @description 打开新增弹窗
   */
  const showAddModal = () => {
    addModalRef.value.open({ entityId: businessEntity?.value.id });
  };
  /**
   * @method
   * @description 新增弹窗提交
   */
  const addModalSubmit = async (reqdata: any) => {
    try {
      if (sqlEditorAddRef.value.getEditorValue().length === 0) {
        Notification.warning({
          content: 'SQL语句不能为空！',
        });
      } else {
        reqdata.defineSql = sqlEditorAddRef.value.getEditorValue();
        const res = (await addSQLRelevanceEntityRecord(reqdata)) as any;
        if (res.code === 200) {
          Notification.success({
            content: '保存成功！',
          });
          addModalRef.value.close();
        } else {
          Notification.error({
            title: '保存失败！',
            content: res.message,
          });
        }
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @description 打开修改业务实体与SQL关系弹窗
   */
  const showEditModal = (record: BusinessEntityRecord) => {
    currentRecord.value = record;
    editModalRef.value.open(record);
  };
  /**
   * @method
   * @description 修改弹窗提交
   */
  const editModalSubmit = async (reqdata: SQLRelevanceEntityRecord) => {
    try {
      if (sqlEditorEditRef.value.getEditorValue().length === 0) {
        Notification.warning({
          content: 'SQL语句不能为空！',
        });
      } else {
        reqdata.defineSql = sqlEditorEditRef.value.getEditorValue();
        const res = (await editSQLRelevanceEntityRecord(reqdata)) as any;
        if (res.code === 200) {
          Notification.success({
            content: '修改成功！',
          });
          editModalRef.value.close();
        } else {
          Notification.error({
            title: '修改失败！',
            content: res.message,
          });
        }
      }
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      searchRef.value.handleSubmit(); // 与搜索结果保持一致
    }
  };
  /**
   * @description 数据预览
   * @param record
   */
  const showPreviewJsonModal = async (record: SQLRelevanceEntityRecord) => {
    const req = {
      searchParams: {
        /* user_code: 199439, */
      },
    };
    const result = await executeSQLRelevanceEntityRecord(
      record.id as string,
      req
    );
    previewJsonRecord.value = JSON.stringify(result, null, '\t'); // json格式化展示
    previewJsonModalRef.value.open();
  };
  /**
   * onMounted
   */
  onMounted(() => {
    getTbData();
  });
</script>
